<template>
  <XhhTable
    ref="table"
    :columns="columns"
    :api="api"
    :form-config="formConfig"
    :params="formConfig.form"
    unique-id="value-set-list-table"
    is-pagination
    stripe
    checkbox
    :row-class-name="handleRowClassName"
    :importConfig="importConfig"
    :showConfig="false"
    @delete="handleDelete"
    @del="handleDel"
    @disableRow="handleDisableRow"
    @enableRow="handleEnableRow"
    @export="handleExport"
    @addValueSet="handleAddValueSet"
  ></XhhTable>
  <XhhDialog
    v-model="dialogVisible"
    title="新增值"
    width="700px"
    @confirm="handleConfirmAddValueSet"
  >
    <XhhForm
      :schema="formConfig.dialogSchema"
      v-model="dialogFormValue"
      inline
      v-bind="formConfig.dialogFormProps"
      :showFormButton="false"
      :defaultSearch="false"
      :isGrid="true"
    ></XhhForm>
  </XhhDialog>
</template>
<script setup>
import { ref, watch } from 'vue'
import req from '@/utils/req/axios'
import { tip, tipBox } from '@tip'
import urls from '@/utils/constants/urls.js'
import { downloadFile } from '@/utils/common/window/index.js'
import { filterFrom, statusFormatter } from '@/utils/common/table/formatters'
import { requiredRule } from '@/utils/common/form'
import { cloneDeep } from 'lodash-unified'
import { showOverflowTooltip } from '@/utils/constants/utils'

const table = ref()
const onlySearchSetType = ref(false)

const allColumns = [
  {
    prop: 'setCode',
    label: '集编码',
    width: 160,
  },
  {
    prop: 'setName',
    label: '集名称',
  },
  {
    prop: 'summary',
    label: '概览',
    ...showOverflowTooltip,
    width: 160,
  },
  {
    prop: 'code',
    label: '值编码',
  },
  {
    prop: 'name',
    label: '值名称',
  },
  {
    prop: 'parentSetCode',
    label: '父集编码',
    width: 120,
  },
  {
    prop: 'parentSetName',
    label: '父集名称',
    width: 120,
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    formatter: statusFormatter,
  },
  {
    prop: 'op',
    label: '操作',
    buttons({ row }) {
      return [
        ...(onlySearchSetType.value
          ? []
          : [
              {
                prop: 'addValueSet',
                label: '新增值',
                type: 'primary',
              },
              'edit',
              'view',
              {
                // status 1 表示已启用 其他表示已停用
                prop: row.status === '1' ? 'disableRow' : 'enableRow',
                label: row.status === '1' ? '停用' : '启用',
                class: row.status === '1' ? 'red' : 'green',
              },
            ]),
        'delete',
      ]
    },
    width: 330,
  },
]

const columns = ref(cloneDeep(filterFrom(allColumns, ['summary'], false)))
// const columns = ref(cloneDeep(allColumns))
const api = {
  async request(params) {
    onlySearchSetType.value = !!params.onlySearchSetType
    const { total, data } = await req.post(
      urls.v1.system.valueSet.listBySetCode,
      {
        status: '', // 查询全部状态的
        ...params,
        isPagination: true,
        isLike: true,
      },
      {
        _forceWithoutCache: true,
      },
    )
    return {
      total,
      data,
    }
  },
}
const formConfig = {
  form: {},
  schema: [
    {
      prop: 'setCode',
      label: '集编码',
    },
    {
      prop: 'setName',
      label: '集名称',
    },
    {
      prop: 'code',
      label: '值编码',
    },
    {
      prop: 'name',
      label: '值名称',
    },
    {
      prop: 'parentSetCode',
      label: '父集编码',
      config: {
        hidden: true,
      },
    },
    {
      prop: 'parentSetName',
      label: '父集名称',
      config: {
        hidden: true,
      },
    },
    {
      prop: 'onlySearchSetType',
      label: '只查询值集类型',
      comp: 'el-checkbox',
    },
  ],
  queryFormProps: {},
  // 如果配置了dialogForm，则新增按钮会自动弹出
  dialogForm: {},
  dialogSchema: [
    {
      prop: 'setCode',
      label: '集编码',
    },
    {
      prop: 'setName',
      label: '集名称',
    },
    {
      prop: 'code',
      label: '值编码',
    },
    {
      prop: 'name',
      label: '值名称',
    },
    {
      prop: 'parentSetCode',
      label: '父集编码',
    },
    {
      prop: 'parentSetName',
      label: '父集名称',
    },
  ],
  dialogFormProps: {
    // dev13及以后可以删除此属性
    rules: {
      ...requiredRule('setCode'),
      ...requiredRule('setName'),
      ...requiredRule('code'),
      ...requiredRule('name'),
    },
  },
  dialogProps: {
    async onConfirm() {
      // todo 验证表单
      await table.value.validDialogForm()
      // 如果验证失败，直接就在内部抛出错误了，下边的代码不会走了
      // 获取表单数据
      // 整理表单数据
      let url
      // 发送请求
      if (table.value.dialogFormMode === 'add') {
        // 新增
        url = urls.v1.system.valueSet.add
      } else if (table.value.dialogFormMode === 'edit') {
        // 编辑
        url = urls.v1.system.valueSet.update
      }
      // 表单数据
      const params = {
        ...table.value.dialogForm,
      }
      await req.post(url, params)
      // 关闭弹窗
      table.value.closeFormDialog()
      // 刷新列表
      table.value.searchData(true)
    },
  },
}

const importConfig = {
  api: {
    async requestTemplate() {
      const res = await req.post(
        urls.v1.system.valueSet.exportTemplate,
        {},
        {
          responseType: 'blob',
        },
      )
      return res.data
    },
    requestImport(formData, headers) {
      return req.post(urls.v1.system.valueSet.import, formData, {
        headers,
        _isReturnOrigin: true,
      })
    },
  },
}

watch(onlySearchSetType, (val) => {
  // 只查询值集类型
  if (val) {
    columns.value = cloneDeep(filterFrom(allColumns, ['code', 'name'], false))
  } else {
    columns.value = cloneDeep(allColumns)
  }
})

const dialogVisible = ref(false)
const dialogFormValue = ref({})

async function handleConfirmAddValueSet() {
  await req.post(urls.v1.system.valueSet.add, dialogFormValue.value)
  dialogVisible.value = false
  // 刷新列表
  table.value.searchData(true)
}

/**
 * 单个删除
 * @param row
 * @returns {Promise<void>}
 */
async function handleDelete({ row }) {
  if (onlySearchSetType.value) {
    await req.post(urls.v1.system.valueSet.delBySetCode, { setCode: row.setCode })
  } else {
    await req.post(urls.v1.system.valueSet.del, { id: row.id })
  }
  table.value.searchData(true)
}

/**
 * 批量删除
 * @returns {Promise<void>}
 */
async function handleDel() {
  if (!table.value.checkedRows?.length) {
    tip({ message: '请选择要删除的行', type: 'error' })
    return
  }
  await req.post(
    onlySearchSetType.value ? urls.v1.system.valueSet.delBySetCode : urls.v1.system.valueSet.del,
    {
      ids: table.value.checkedRows.map((item) => item.id),
    },
  )
  table.value.searchData()
}

async function handleAddValueSet({ row }) {
  dialogFormValue.value = {
    setCode: row.setCode,
    setName: row.setName,
    parentSetCode: row.parentSetCode,
    parentSetName: row.parentSetName,
  }
  dialogVisible.value = true
}

/**
 * 导出excel
 * @returns {Promise<void>}
 */
async function handleExport() {
  const dataLength = table.value.checkedRows?.length
  // 若存在选中的数据，则导出选中的数据，否则按条件导出数据
  const confirm = await tipBox.confirm(
    dataLength ? `确认要导出选中的${dataLength}条数据吗？` : `确认要根据查询条件导出数据吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  if (confirm === 'confirm') {
    const res = await req.post(
      urls.v1.system.valueSet.export,
      {
        ...(dataLength
          ? { ids: table.value.checkedRows.map((item) => item.id) }
          : { ...table.value.queryForm }),
      },
      { responseType: 'blob' },
    )
    // 将流转化为文件进行下载 todo 文件名称从后端获取，从headers中获取
    downloadFile({ blob: res.data, fileName: '值集列表.xlsx' })
  }
}

async function handleStatusRow({ row, status, message, label }) {
  const confirm = await tipBox.confirm(`确认要执行${label}操作吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  if (confirm === 'confirm') {
    await req.post(
      urls.v1.system.valueSet.update,
      { id: row.id, status },
      { _showSuccessTip: false },
    )
    tip({ message, type: 'success' })
    table.value.searchData(true)
  }
}

async function handleDisableRow({ row }) {
  await handleStatusRow({ row, status: '2', message: '停用成功', label: '停用' })
}

async function handleEnableRow({ row }) {
  await handleStatusRow({ row, status: '1', message: '启用成功', label: '启用' })
}

function handleRowClassName({ row }) {
  return row.status === '1' ? 'enable-row' : 'disable-row'
}
</script>
